package com.alibaba.citrus.cr.order.open.api.facade.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.log.CommonErrorCode;
import com.alibaba.citrus.cr.order.open.api.facade.common.until.CheckUtil;
import com.alibaba.citrus.cr.order.open.api.facade.convert.WarehouseConvert;
import com.alibaba.citrus.cr.unified.inventory.utils.ToolUtil;
import com.alibaba.cz.base.model.store.CargoZoneSDO;
import com.alibaba.cz.base.tool.DateFormatUtil;
import com.alibaba.cz.base.tool.FeatureUtil;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.feature.Features;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByCodes2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByCodes2Response;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIds2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIds2Response;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crunifiedinventory.api.allocateorderread.service.AllocateOrderReadService;
import com.epoch.app.crunifiedinventory.domain.allocateorder.dto.AllocateOrderLoadListRequest;
import com.epoch.app.crunifiedinventory.domain.allocateorder.model.AllocateOrder;
import com.epoch.app.crunifiedinventory.domain.allocateorder.service.AllocateOrderService;
import com.epoch.app.crunifiedinventory.dto.request.AllocateOrderDetailSearchRequest;
import com.epoch.app.crunifiedinventory.dto.request.AllocateOrderDetailsQueryRequest;
import com.epoch.app.crunifiedinventory.dto.response.AllocateOrderDetailVO;
import com.epoch.app.crunifiedinventory.dto.response.AllocateOrderDetailsQueryResponse;
import com.epoch.app.crunifiedinventory.model.enums.AllocateOrderStatus;
import com.epoch.app.crunifiedinventory.model.enums.FulfillmentTypeEnum;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateOrderShipTypeEnums;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateOrderTypeEnum;
import com.epoch.app.crunifiedinventory.sdo.enums.ReasonForRejectionEnum;
import com.epoch.app.crunifiedinventory.sdo.enums.TransportModeEnum;
import com.epoch.app.mninventorycenter.model.dto.*;
import com.epoch.app.mninventorycenter.service.MnInventoryCenterService;
import com.epoch.app.mninventorycenter.transferorderread.service.TransferOrderReadService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: yuXian
 * @description:
 * @DATE 2023/5/20 14:43
 */
@Service
public class TransferOrderReadServiceImpl implements TransferOrderReadService {

    private Log log = Log.getLogger(TransferOrderReadServiceImpl.class);

    @Resource
    private AllocateOrderReadService allocateOrderReadService;

    @Resource
    private MnInventoryCenterService mnInventoryCenterService;
    @Resource
    private WarehouseConvert warehouseConvert;
    @Resource
    private AllocateOrderService allocateOrderService;
    @Resource
    private BaseDataService baseDataService;

    private static final String TRUE = "1";
    private static final String FALSE = "0";
    private static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static final String FROM_SYS_GROUP = "fromSys";
    private static final String BUSINESS_TYPE_GROUP = "businessType";
    private static final String ORDER_TAG = "allocateOrderTag";


    @SneakyThrows
    @Override
    @FacadeInvoker(value = "调拨单列表")
    public Result<TransOrdListQueryResponse> queryTransferOrderList(TransOrdListQueryRequest request) {
        log.info("queryTransferOrderList_request:{}", JSON.toJSONString(request));
        StopWatch stopWatch = new StopWatch();
        TransOrdListQueryResponse response = new TransOrdListQueryResponse();
        stopWatch.start("checkQueryTransferOrderList");
        // 页码、条数默认值
        fillRequestDefaultValue(request);
        String message = checkQueryTransferOrderList(request);
        stopWatch.stop();
        if(message !=null){
            return Result.fail( "OTS-03-001-00-15-101", message);
        }
        stopWatch.start("trim");
        ToolUtil.trim(request);
        stopWatch.stop();
        AllocateOrderDetailSearchRequest allocateOrderDetailSearchRequest = new AllocateOrderDetailSearchRequest();
//        BeanUtils.copyProperties(request, allocateOrderDetailSearchRequest);
        allocateOrderDetailSearchRequest.setCode(request.getTransferOrderCode());
        allocateOrderDetailSearchRequest.setType(request.getTransferOrderType());
        allocateOrderDetailSearchRequest.setScItemCode(request.getGoodsCode());
        if (CollectionUtils.isNotEmpty(request.getGoodsCodeList())){
            allocateOrderDetailSearchRequest.setScItemCodeList(request.getGoodsCodeList());
        }
        if (StringUtils.isNotBlank(request.getClose())){
            allocateOrderDetailSearchRequest.setClose(Integer.parseInt(request.getClose()));
        }
        allocateOrderDetailSearchRequest.setCloseCode(request.getCloseCode());

        if(StringUtils.isNotBlank(request.getReceiveLogicWareCode())){
            stopWatch.start("getWarehouseInfo-1");
            String receiveWarehouseId = getWarehouseInfo(request.getReceiveLogicWareCode());
            stopWatch.stop();
            if(StringUtils.isEmpty(receiveWarehouseId)){
                Result<TransOrdListQueryResponse> success = Result.success(response);
                success.setTotal(0);
                fillResult(success);
                return success;
            }
            allocateOrderDetailSearchRequest.setReceiveAreaId(receiveWarehouseId);
//            allocateOrderDetailSearchRequest.setReceiveWarehouseId(receiveWarehouseId);
        }
        if(StringUtils.isNotBlank(request.getDeliveryLogicWareCode())){
            stopWatch.start("getWarehouseInfo-2");
            String shipWarehouseId = getWarehouseInfo(request.getDeliveryLogicWareCode());
            stopWatch.stop();
            if(StringUtils.isEmpty(shipWarehouseId)){
                Result<TransOrdListQueryResponse> success = Result.success(response);
                success.setTotal(0);
                fillResult(success);
                return success;
            }
            allocateOrderDetailSearchRequest.setShipAreaId(shipWarehouseId);
//            allocateOrderDetailSearchRequest.setShipWarehouseId(shipWarehouseId);
        }
        //todo 收货逻辑仓
        allocateOrderDetailSearchRequest.setPage(request.getPage());
        allocateOrderDetailSearchRequest.setSize(request.getSize());
//        allocateOrderDetailSearchRequest.setDocDateBegin(request.getGmtCreateStart());
//        allocateOrderDetailSearchRequest.setDocDateEnd(request.getGmtCreateEnd());
        //开始时间
        if (StrUtil.isNotBlank(request.getGmtCreateStart())){
            long createTimeBeginLon = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .parse(request.getGmtCreateStart()).getTime();
            allocateOrderDetailSearchRequest.setCreateTimeBeginLong(createTimeBeginLon);
        }
        //结束时间
        if (StrUtil.isNotBlank(request.getGmtCreateEnd())){
            long endTimeBeginLon = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .parse(request.getGmtCreateEnd()).getTime();
            allocateOrderDetailSearchRequest.setCreateTimeEndLong(endTimeBeginLon);
        }
        if (StringUtils.isNotBlank(request.getFromSys())){
            allocateOrderDetailSearchRequest.setFromSys(request.getFromSys());
        }
        if (StringUtils.isNotBlank(request.getBusinessType())){
            allocateOrderDetailSearchRequest.setBusinessType(request.getBusinessType());
        }

        //提报组织编码转换 这里仍旧使用id吧
        if (StringUtils.isNotBlank(request.getApplyOrgCode()) || StringUtils.isNotBlank(request.getApplyOrgId())){
            stopWatch.start("baselineGetOrganizationByCodes2");
            BaselineGetOrganizationByCodes2Request byCodes2Request = new BaselineGetOrganizationByCodes2Request();
            byCodes2Request.setIds(Lists.newArrayList(request.getApplyOrgCode(),request.getApplyOrgId()).stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()));
            BaselineGetOrganizationByCodes2Response byCodes2Response = baseDataService.baselineGetOrganizationByCodes2(byCodes2Request);
            stopWatch.stop();
            if (byCodes2Response == null || CollectionUtils.isEmpty(byCodes2Response.getResult())){
                log.info("queryTransferOrderList_applyOrg_error");
                Result<TransOrdListQueryResponse> success = Result.success(response);
                success.setTotal(0);
                fillResult(success);
                return success;
            }
            allocateOrderDetailSearchRequest.setApplyOrgId(byCodes2Response.getResult().get(0).getId());
        }

        //查询入参 以下是仓库相关的
        stopWatch.start("getCargoZoneSDOMapByCodes");
        List<String> queryWarehouseCodes = Stream.of(Stream.of(request.getDeliveryLogicWareCode()),
                        CollectionUtils.isEmpty(request.getDeliveryLogicWarehouseCodeList()) ? null : request.getDeliveryLogicWarehouseCodeList().stream(),
                        Stream.of(request.getReceiveLogicWareCode()),
                        CollectionUtils.isEmpty(request.getReceiveLogicWarehouseCodeList()) ? null : request.getReceiveLogicWarehouseCodeList().stream()
//                        Stream.of(request.getFreightYardCode())
                )
                .flatMap(Function.identity())
                .filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        log.info("getCargoZoneSDOMap_request:{}",JSON.toJSONString(queryWarehouseCodes));
        Map<String, CargoZoneSDO> cargoZoneSDOMap = warehouseConvert.getCargoZoneSDOMapByCodes(queryWarehouseCodes);
        stopWatch.stop();
        log.info("getCargoZoneSDOMap_response:{}",JSON.toJSONString(cargoZoneSDOMap));
//        if (StringUtils.isNotBlank(request.getDeliveryLogicWareCode())){
//            CargoZoneSDO cargoZoneSDO = cargoZoneSDOMap.get(request.getDeliveryLogicWareCode());
//            if (Objects.isNull(cargoZoneSDO)){
//                Result<TransOrdListQueryResponse> success = Result.success(response);
//                success.setTotal(0);
//                return success;
//            }else {
//                allocateOrderDetailSearchRequest.setShipAreaId(cargoZoneSDO.getId());
//            }
//        }

        if (CollectionUtils.isNotEmpty(request.getDeliveryLogicWarehouseCodeList())){
            List<String> logicAreaIds = Nullable.stream(cargoZoneSDOMap.values()).filter(cargoZoneSDO ->
                            request.getDeliveryLogicWarehouseCodeList().contains(cargoZoneSDO.getCode()))
                    .map(CargoZoneSDO::getId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(logicAreaIds)){
                log.info("queryTransferOrderList_getDeliveryLogicWarehouseCodeList_error");
                Result<TransOrdListQueryResponse> success = Result.success(response);
                success.setTotal(0);
                fillResult(success);
                return success;
            }else {
                allocateOrderDetailSearchRequest.setShipAreaIdList(logicAreaIds);
            }
        }
//        if (StringUtils.isNotBlank(request.getReceiveLogicWareCode())){
//            CargoZoneSDO cargoZoneSDO = cargoZoneSDOMap.get(request.getReceiveLogicWareCode());
//            if (Objects.isNull(cargoZoneSDO)){
//                Result<TransOrdListQueryResponse> success = Result.success(response);
//                success.setTotal(0);
//                return success;
//            }else {
//                allocateOrderDetailSearchRequest.setReceiveAreaId(cargoZoneSDO.getId());
//            }
//        }
        if (CollectionUtils.isNotEmpty(request.getReceiveLogicWarehouseCodeList())){
            List<String> logicAreaIds = Nullable.stream(cargoZoneSDOMap.values()).filter(cargoZoneSDO ->
                            request.getReceiveLogicWarehouseCodeList().contains(cargoZoneSDO.getCode()))
                    .map(CargoZoneSDO::getId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(logicAreaIds)){
                log.info("queryTransferOrderList_getReceiveLogicWarehouseCodeList_error");
                Result<TransOrdListQueryResponse> success = Result.success(response);
                success.setTotal(0);
                fillResult(success);
                return success;
            }else {
                allocateOrderDetailSearchRequest.setReceiveAreaIdList(logicAreaIds);
            }
        }
        if (StringUtils.isNotBlank(request.getFreightYardCode())){
            allocateOrderDetailSearchRequest.setFreightYardCode(request.getFreightYardCode());
//            CargoZoneSDO cargoZoneSDO = cargoZoneSDOMap.get(request.getFreightYardCode());
//            if (Objects.isNull(cargoZoneSDO)){
//                log.info("queryTransferOrderList_getFreightYardCode_error");
//                Result<TransOrdListQueryResponse> success = Result.success(response);
//                success.setTotal(0);
//                return success;
//            }else {
//                allocateOrderDetailSearchRequest.setFreightYardId(cargoZoneSDO.getId());
//            }
        }

        if (StringUtils.isNotBlank(request.getDeliveryFactoryCode())){
            allocateOrderDetailSearchRequest.setDeliveryFactoryCode(request.getDeliveryFactoryCode());
        }
        if (StringUtils.isNotBlank(request.getDeliveryStorageLocationCode())){
            allocateOrderDetailSearchRequest.setDeliveryStorageLocationCode(request.getDeliveryStorageLocationCode());
        }
        if (StringUtils.isNotBlank(request.getReceiveFactoryCode())){
            allocateOrderDetailSearchRequest.setReceiveFactoryCode(request.getReceiveFactoryCode());
        }
        if (StringUtils.isNotBlank(request.getReceiveStorageLocationCode())){
            allocateOrderDetailSearchRequest.setReceiveStorageLocationCode(request.getReceiveStorageLocationCode());
        }

        /** 以上是仓库相关  **/
        allocateOrderDetailSearchRequest.setCode(request.getTransferOrderCode());
        allocateOrderDetailSearchRequest.setThirdAllocateOrderId(request.getThirdAllocateOrderId());
        allocateOrderDetailSearchRequest.setOutAllocateOrderId(request.getOutOrderCode());
        allocateOrderDetailSearchRequest.setAllocateApplyOrderCode(request.getAllocateApplyOrderCode());
        allocateOrderDetailSearchRequest.setRelatedAllocateOrderCode(request.getRelatedAllocateOrderCode());
        if (request.getTransferOrderType() != null){
            allocateOrderDetailSearchRequest.setTypeList(Lists.newArrayList(request.getTransferOrderType().toString()));
        }
        //TODO 这里提报组织id是code转换过后的
//        if (StringUtils.isNotBlank(request.getApplyOrgId())){
//            allocateOrderDetailSearchRequest.setApplyOrgId(request.getApplyOrgId());
//        }
        allocateOrderDetailSearchRequest.setFulfillmentTypeCode(request.getFulfillmentTypeCode());
        allocateOrderDetailSearchRequest.setOrderTag(request.getOrderTag());
//        allocateOrderDetailSearchRequest.setFreightYardId();
        if (CollectionUtils.isNotEmpty(request.getStatusList())){
            allocateOrderDetailSearchRequest.setStatusList(request.getStatusList());
        }
//        allocateOrderDetailSearchRequest.setCreator(request.getCreator());
        if (StringUtils.isNotBlank(request.getGmtCreateStart())){
            long createTime = DateFormatUtil.parseStrToDate(request.getGmtCreateStart(), "yyyy-MM-dd HH:mm:ss").getTime();
            allocateOrderDetailSearchRequest.setCreateTimeBeginLong(createTime);
        }
        if (StringUtils.isNotBlank(request.getGmtCreateEnd())){
            long endTime = DateFormatUtil.parseStrToDate(request.getGmtCreateEnd(), "yyyy-MM-dd HH:mm:ss").getTime();
            allocateOrderDetailSearchRequest.setCreateTimeEndLong(endTime + 1);
        }
//        allocateOrderDetailSearchRequest.setModifier(request.getModifier());
        if (StringUtils.isNotBlank(request.getGmtModifiedStart())){
            long startTime = DateFormatUtil.parseStrToDate(request.getGmtModifiedStart(), "yyyy-MM-dd HH:mm:ss").getTime();
            allocateOrderDetailSearchRequest.setGmtModifiedStartLong(startTime);
        }
        if (StringUtils.isNotBlank(request.getGmtModifiedEnd())){
            long endTime = DateFormatUtil.parseStrToDate(request.getGmtModifiedEnd(), "yyyy-MM-dd HH:mm:ss").getTime();
            allocateOrderDetailSearchRequest.setGmtModifiedEndLong(endTime +1);
        }
        if (StringUtils.isNotBlank(request.getReturnFlag())){
            allocateOrderDetailSearchRequest.setReturnOrder(TRUE.equals(request.getReturnFlag()));
        }
        allocateOrderDetailSearchRequest.setShipMethod(request.getShipMethodCode());
        if (StringUtils.isNotBlank(request.getGoodsCode())){
            allocateOrderDetailSearchRequest.setScItemCode(request.getGoodsCode());
        }
        if (CollectionUtils.isNotEmpty(request.getGoodsCodeList())){
            allocateOrderDetailSearchRequest.setScItemCodeList(request.getGoodsCodeList());
        }
//        if (CollectionUtils.isNotEmpty(request.getDeliveryLogicWareCodeList())){
//            allocateOrderDetailSearchRequest.setDeliveryLogicWareCodeList(request.getDeliveryLogicWareCodeList());
//        }
//        if (CollectionUtils.isNotEmpty(request.getDeliveryLogicWarehouseCodeList())){
//            allocateOrderDetailSearchRequest.setDeliveryLogicWarehouseCodeList(request.getDeliveryLogicWarehouseCodeList());
//        }
//        if (CollectionUtils.isNotEmpty(request.getReceiveLogicWarehouseCodeList())){
//            allocateOrderDetailSearchRequest.setReceiveLogicWarehouseCodeList(request.getReceiveLogicWarehouseCodeList());
//        }
//        if (StringUtils.isNotBlank(request.getFreightYardCode())){
//            allocateOrderDetailSearchRequest.setFreightYardCode(request.getFreightYardCode());
//        }
        if (StringUtils.isNotBlank(request.getDeliveryFactoryCode())){
            allocateOrderDetailSearchRequest.setDeliveryFactoryCode(request.getDeliveryFactoryCode());
        }
        if (StringUtils.isNotBlank(request.getReceiveFactoryCode())){
            allocateOrderDetailSearchRequest.setReceiveFactoryCode(request.getReceiveFactoryCode());
        }
        if (StringUtils.isNotBlank(request.getDeliveryStorageLocationCode())){
            allocateOrderDetailSearchRequest.setDeliveryStorageLocationCode(request.getDeliveryStorageLocationCode());
        }
        if (StringUtils.isNotBlank(request.getReceiveStorageLocationCode())){
            allocateOrderDetailSearchRequest.setReceiveStorageLocationCode(request.getReceiveStorageLocationCode());
        }

        if (CollectionUtils.isNotEmpty(request.getStatusList())){
            allocateOrderDetailSearchRequest.setStatusList(request.getStatusList());
        }
        if (CollectionUtils.isNotEmpty(request.getDetailStatusList())){
            allocateOrderDetailSearchRequest.setLineStatusList(request.getDetailStatusList());
        }
        if (request.getShipMethodCode() != null){
            allocateOrderDetailSearchRequest.setShipMethod(request.getShipMethodCode());
        }
        if (StringUtils.isNotBlank(request.getReturnFlag())){
            allocateOrderDetailSearchRequest.setReturnOrder(TRUE.equals(request.getReturnFlag()));
        }
        if (StringUtils.isNotBlank(request.getClose())){
            allocateOrderDetailSearchRequest.setClose(Integer.parseInt(request.getClose()));
        }
        if (StringUtils.isNotBlank(request.getCloseCode())){
            allocateOrderDetailSearchRequest.setCloseCode(request.getCloseCode());
        }
        if (StringUtils.isNotBlank(request.getCreator())){
            allocateOrderDetailSearchRequest.setMainCreator(request.getCreator());
        }
        if (StringUtils.isNotBlank(request.getModifier())){
            allocateOrderDetailSearchRequest.setMainUpdater(request.getModifier());
        }

        if (StringUtils.isNotBlank(request.getOutAllocateApplyOrderCode())) {
            allocateOrderDetailSearchRequest.setOutAllocateApplyOrderId(request.getOutAllocateApplyOrderCode());
        }
        if (StringUtils.isNotBlank(request.getHeadRemark())) {
            allocateOrderDetailSearchRequest.setHeadRemark(request.getHeadRemark());
        }
        if (CollectionUtils.isNotEmpty(request.getShipMethodCodeList())) {
            allocateOrderDetailSearchRequest.setShipMethodCodeList(request.getShipMethodCodeList());
        }
        if (CollectionUtils.isNotEmpty(request.getBizUnitCodeList())) {
            allocateOrderDetailSearchRequest.setBizUnitCodeList(request.getBizUnitCodeList());
        }
        //调出业务单元列表
        if (CollectionUtils.isNotEmpty(request.getTransferOutBizUnitCodeList())){
            allocateOrderDetailSearchRequest.setTransferOutBizUnitCodeList(request.getTransferOutBizUnitCodeList());
        }
        //原调拨单类型
        if (StringUtils.isNotBlank(request.getOriginTransferOrderType())){
            allocateOrderDetailSearchRequest.setOriginTransferOrderType(request.getOriginTransferOrderType());
        }
        //原sap调拨单号
        if (StringUtils.isNotBlank(request.getOriginOutOrderCode())){
            allocateOrderDetailSearchRequest.setOriginOutOrderCode(request.getOriginOutOrderCode());
        }
        //调拨单类型列表
        if (CollectionUtils.isNotEmpty(request.getTransferOrderTypeList())){
            allocateOrderDetailSearchRequest.setTypeList(request.getTransferOrderTypeList());
        }
        //履约方式列表
        if (CollectionUtils.isNotEmpty(request.getFulfillmentTypeCodeList())){
            allocateOrderDetailSearchRequest.setFulfillmentTypeCodeList(request.getFulfillmentTypeCodeList());
        }

        log.info("TransferOrderReadServiceImpl——拓传请求参数：{}",allocateOrderDetailSearchRequest);
        stopWatch.start("queryTransferOrderSearch");
        Result<List<AllocateOrderDetailVO>> listResult = allocateOrderReadService.queryTransferOrderSearch(allocateOrderDetailSearchRequest);
        stopWatch.stop();
        log.info("TransferOrderReadServiceImpl——拓转响应结果：{}",listResult);
        List<AllocateOrderDetailVO> result = listResult.getResult();
        if (CollectionUtil.isEmpty(result)) {
            Result<TransOrdListQueryResponse> success = Result.success(null);
            success.setTotal(listResult.getTotal());
            fillResult(success);
            return success;
        }
        //获取提报组织编码
        Map<String, OrganizationSDO> orgMap = Maps.newHashMap();
        if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
            List<String> orgIds = listResult.getResult().stream().map(AllocateOrderDetailVO::getApplyOrgId).filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(orgIds)){
                stopWatch.start("baselineGetOrganizationByIds2");
                BaselineGetOrganizationByIds2Request byIds2Request = new BaselineGetOrganizationByIds2Request();
                byIds2Request.setIds(orgIds);
                BaselineGetOrganizationByIds2Response byIds2Response = baseDataService.baselineGetOrganizationByIds2(byIds2Request);
                stopWatch.stop();
                Nullable.stream(byIds2Response.getResult()).forEach(organizationSDO -> orgMap.put(organizationSDO.getId(),organizationSDO));
            }
        }
        // 货场仓map
        Map<String,CargoZoneSDO> cargoZoneSDOCodeMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(result)){
            List<String> freightYardIds = result.stream().map(AllocateOrderDetailVO::getFreightYardId).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
            //这里是code
            log.info("getCargoZoneSDOMap_request:{}",JSON.toJSONString(freightYardIds));
            if (CollectionUtils.isNotEmpty(freightYardIds)){
                stopWatch.start("getCargoZoneSDOMap");
                Map<String, CargoZoneSDO> zoneSDOMap = warehouseConvert.getCargoZoneSDOMapByCodes(freightYardIds);
                stopWatch.stop();
                if (MapUtils.isNotEmpty(zoneSDOMap)){
                    cargoZoneSDOCodeMap.putAll(zoneSDOMap);
                }
            }
        }

        stopWatch.start("convert_transOrdInfoResponse");
        List<TransOrdInfoResponse> transOrdInfoResponses = result.stream().map(x -> {
            TransOrdInfoResponse transOrdInfoResponse = new TransOrdInfoResponse();
            BeanUtils.copyProperties(x, transOrdInfoResponse);
            transOrdInfoResponse.setFromSys(x.getFromSys());
            transOrdInfoResponse.setBusinessType(x.getBusinessType());
            transOrdInfoResponse.setTransferOrderCode(x.getCode());
            transOrdInfoResponse.setDetailNo(x.getLineNo());
            transOrdInfoResponse.setTransferOrderType(x.getType());
//            transOrdInfoResponse.setTransferOrderTypeName(); //调拨单类型名称
            transOrdInfoResponse.setTransferOrderTypeName(x.getTypeDesc());
            transOrdInfoResponse.setReceiveLogicWarehouseName(x.getReceiveAreaName());
            //transOrdInfoResponse.setReceiveLogicWareHouseCode(x.getReceiveAreaId());
            transOrdInfoResponse.setReceiveLogicWareHouseCode(x.getReceiveAreaCode());
            transOrdInfoResponse.setDeliveryLogicWareHouseName(x.getShipAreaName());
            //transOrdInfoResponse.setDeliveryLogicWareCode(x.getShipAreaId());
            transOrdInfoResponse.setDeliveryLogicWareCode(x.getShipAreaCode());
            if (Objects.nonNull(x.getDocDate())) {
                transOrdInfoResponse.setOrderDate(new SimpleDateFormat("yyyy-MM-dd").format(x.getDocDate()));
            }

            transOrdInfoResponse.setExpectedDeliveryDate(x.getExpectedDeliveryDateStr());
            transOrdInfoResponse.setGoodsCode(x.getScItemCode());
            transOrdInfoResponse.setGoodsName(x.getScItemName());
            transOrdInfoResponse.setQuantity(x.getQuantity());
            transOrdInfoResponse.setHeadRemark(x.getRemark());
            transOrdInfoResponse.setDetailRemark(x.getLineRemark());
            //已下补足新增字段
            transOrdInfoResponse.setOutOrderCode(x.getOutAllocateOrderId());
            transOrdInfoResponse.setAllocateApplyOrderCode(x.getAllocateApplyOrderCode());
            transOrdInfoResponse.setRelatedAllocateOrderCode(x.getRelatedAllocateOrderCode());
            if (orgMap.containsKey(x.getApplyOrgId())){
                transOrdInfoResponse.setApplyOrgId(Optional.ofNullable(orgMap.get(x.getApplyOrgId())).map(OrganizationSDO::getCode).orElse(null));
            }
//            transOrdInfoResponse.setApplyOrgId(x.getApplyOrgId());

            transOrdInfoResponse.setApplyOrgName(x.getApplyOrgName());
            //销售组织
            transOrdInfoResponse.setSaleOrganizationCode(x.getSaleOrganizationCode());
            transOrdInfoResponse.setProductGroup(x.getProductGroup());
            transOrdInfoResponse.setFulfillmentTypeCode(x.getFulfillmentTypeCode());
            transOrdInfoResponse.setAutoFulfillment(x.getAutoFulfillment());
            transOrdInfoResponse.setPriority(x.getPriority());
            if (StringUtils.isNotBlank(x.getOrderTag())){
                transOrdInfoResponse.setOrderTag(Arrays.asList(x.getOrderTag().split(",")));
            }
            transOrdInfoResponse.setDeliveryLogicWareCode(x.getShipAreaCode());
            transOrdInfoResponse.setDeliveryLogicWareHouseName(x.getShipAreaName());
            transOrdInfoResponse.setDeliveryPhysicalWareCode(x.getShipWarehouseCode());
            transOrdInfoResponse.setDeliveryPhysicalWareName(x.getShipWarehouseName());
            transOrdInfoResponse.setReceiveLogicWareHouseCode(x.getReceiveAreaCode());
            transOrdInfoResponse.setReceiveLogicWarehouseName(x.getReceiveAreaName());
            transOrdInfoResponse.setReceivePhysicalWareCode(x.getReceiveWarehouseCode());
            transOrdInfoResponse.setReceivePhysicalWareName(x.getReceiveWarehouseName());
            transOrdInfoResponse.setReceiveAreaContactor(x.getReceiveAreaContactor());
            transOrdInfoResponse.setReceiveAreaPhone(x.getReceiveAreaPhone());
            transOrdInfoResponse.setReceiveAreaAddress(x.getReceiveAreaAddress());
            transOrdInfoResponse.setReceiveAreaPhone(x.getReceiveAreaPhone());

            //是否货场仓收货怎么判断? 看有没有货场仓?
            transOrdInfoResponse.setFreightYardReceive(x.getFreightYardReceive());
            CargoZoneSDO codeCargoZoneSDO = cargoZoneSDOCodeMap.get(x.getFreightYardId());
            transOrdInfoResponse.setFreightYardCode(x.getFreightYardId());
            if (codeCargoZoneSDO != null){
                transOrdInfoResponse.setFreightYardName(codeCargoZoneSDO.getName());
            }
            transOrdInfoResponse.setStatus(x.getStatus() == null ? null : x.getStatus().toString());
            transOrdInfoResponse.setDetailStatus(x.getDetailStatus());
            transOrdInfoResponse.setCreator(x.getMainCreator());
            transOrdInfoResponse.setGmtCreate(x.getCreateTime() == null ? null : DateFormatUtil.toString(x.getCreateTime(),YYYY_MM_DD_HH_MM_SS));
            transOrdInfoResponse.setUpdater(x.getMainUpdater());
            transOrdInfoResponse.setGmtModified(x.getUpdateTime() == null ? null :DateFormatUtil.toString(x.getUpdateTime(),YYYY_MM_DD_HH_MM_SS));
            //4点前取今天,4点后取明天
//            transOrdInfoResponse.setTakeEffectTime(x.getDocDateStr());
//            transOrdInfoResponse.setOrderDate(x.getDocDateStr());
//            transOrdInfoResponse.setExpectedDeliveryDate(x.getExpectedDeliveryDateStr());
            transOrdInfoResponse.setShipMethod(StringUtils.isBlank(x.getShipMethod()) ? null : "0" + x.getShipMethod());
            transOrdInfoResponse.setShipMethodDesc(x.getShipMethodDesc());
            transOrdInfoResponse.setReturnOrder(x.getReturnOrder());
            transOrdInfoResponse.setTakeEffectTime(x.getDocDateStr());
            transOrdInfoResponse.setOrderDate(x.getDocDateStr());


            //子单
            transOrdInfoResponse.setOutDetailLineNo(x.getOutAllocateOrderLineId());
            transOrdInfoResponse.setAllocateApplyDetailLineNo(x.getAllocateApplyDetailLineNo());

            transOrdInfoResponse.setRelatedAllocateSubOrderId(x.getRelatedAllocateSubOrderId());
            transOrdInfoResponse.setDetailStatus(x.getDetailStatus());
            transOrdInfoResponse.setConfirmQuantity(x.getConfirmQuantity());
            transOrdInfoResponse.setUnit(x.getUnit());
            transOrdInfoResponse.setUnitPrice(x.getUnitPrice());
            transOrdInfoResponse.setProductDate(x.getProductDateStr());
            transOrdInfoResponse.setClosed(x.getClosed());
            //关闭编码
            transOrdInfoResponse.setCloseCode(x.getCloseCode());
            transOrdInfoResponse.setCloseReason(x.getCloseReason());
            if(StringUtils.isNotBlank(x.getDetailFeatures())) {
                Features features = Features.newFeatures(x.getDetailFeatures());
                transOrdInfoResponse.setDetailFeatures(JSON.toJSONString(features.getOriginMap()));
            }
            transOrdInfoResponse.setDetailRemark(x.getLineRemark());
            transOrdInfoResponse.setDeliveryFactoryCode(x.getShipFactoryCode());
            transOrdInfoResponse.setDeliveryStorageLocationCode(x.getShipInventoryCode());
            transOrdInfoResponse.setReceiveFactoryCode(x.getReceiveFactoryCode());
            transOrdInfoResponse.setReceiveStorageLocationCode(x.getReceiveInventoryCode());
            transOrdInfoResponse.setOutAllocateApplyOrderCode(x.getOutAllocateApplyOrderId());
            //主单扩展
            if (StringUtils.isNotBlank(x.getHeadFeatures())){
                Features features = Features.newFeatures(x.getHeadFeatures());
                transOrdInfoResponse.setHeadFeatures(JSON.toJSONString(features.getOriginMap()));
            }
            //确认日期
            transOrdInfoResponse.setConfirmTime(x.getConfirmDateStr());
            //交货日期
            transOrdInfoResponse.setDeliveryDateStr(x.getDeliveryDateStr());
            return transOrdInfoResponse;
        }).collect(Collectors.toList());
        stopWatch.stop();
        response.setData(transOrdInfoResponses);

        log.info("调拨单列表，出参：{}",response);
        ToolUtil.addEmptyString(response);
        Nullable.stream(response.getData()).forEach(ToolUtil::addEmptyString);
        Result<TransOrdListQueryResponse> success = Result.success(response);
        success.setTotal(listResult.getTotal());
        log.info("queryTransferOrderList_cost "+stopWatch.prettyPrint());
        return success;
    }

    private void fillRequestDefaultValue(TransOrdListQueryRequest request) {
        if (request.getPage() == null) {
            request.setPage(1);
        }
        if (request.getSize() == null) {
            request.setSize(10);
        }
    }

    private String checkQueryTransferOrderList(TransOrdListQueryRequest request){
        if(StringUtils.isNotBlank(request.getFromSys()) && request.getFromSys().length() > 16){
            return "来源系统编码长度不能大于16";
        }
        if (StringUtils.isNotBlank(request.getFromSys()) && !checkDictionary(FROM_SYS_GROUP,request.getFromSys())){
            return "来源系统编码不合法";
        }
        if(StringUtils.isBlank(request.getBusinessType())){
            return "业态编码不能为空";
        }
        if(request.getBusinessType().trim().length() >16){
            return "业态编码长度不能大于16";
        }
        if (!checkDictionary(BUSINESS_TYPE_GROUP,request.getBusinessType())){
            return "业态编码不合法";
        }
        if(ObjectUtil.isEmpty(request.getPage())){
            return "分页开始页码不能为空";
        }
        if (request.getPage() <= 0 || request.getPage() > 10000){
            return "分页开始页码面最小为1,且最大不超过10000";
        }
        if(ObjectUtil.isEmpty(request.getSize())){
            return "分页每页条数不能为空";
        }
        if (request.getSize() <= 0 || request.getSize() > 100){
            return "分页每页条数最小为1,且最大不超过100";
        }
        if (StringUtils.isNotBlank(request.getTransferOrderCode()) && request.getTransferOrderCode().trim().length() > 32){
            return "调拨单号长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getThirdAllocateOrderId()) && request.getThirdAllocateOrderId().trim().length() > 32){
            return "来源单号长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getOutOrderCode()) && request.getOutOrderCode().trim().length() > 32){
            return "外部单号长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getAllocateApplyOrderCode()) && request.getAllocateApplyOrderCode().trim().length() > 32){
            return "预报单号长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getRelatedAllocateOrderCode()) && request.getRelatedAllocateOrderCode().trim().length() > 32){
            return "关联单号长度不能超过32";
        }
//        if (request.getTransferOrderType() == null){
//            return "调拨单类型不能为空";
//        }
        if (request.getTransferOrderType() != null && !Arrays.stream(AllocateOrderTypeEnum.values()).anyMatch(allocateOrderTypeEnum ->
                allocateOrderTypeEnum.getType().equals(request.getTransferOrderType()))) {
            return "调拨单类型不合法";
        }
//        if (StringUtils.isBlank(request.getFulfillmentTypeCode())){
//            return "调拨单类型不能为空";
//        }
        if (StringUtils.isNotBlank(request.getApplyOrgId()) && request.getApplyOrgId().trim().length() > 32){
            return "销售组织长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getApplyOrgCode()) && request.getApplyOrgCode().trim().length() > 32){
            return "销售组织长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getFulfillmentTypeCode()) && request.getFulfillmentTypeCode().trim().length()>3){
            return "履约方式长度不能超过3";
        }
        if (StringUtils.isNotBlank(request.getFulfillmentTypeCode()) && !Arrays.stream(FulfillmentTypeEnum.values()).anyMatch(allocateOrderTypeEnum ->
                allocateOrderTypeEnum.getValue().toString().equals(request.getFulfillmentTypeCode().trim()))) {
            return "履约方式不合法";
        }
        if (StringUtils.isNotBlank(request.getOrderTag()) && request.getOrderTag().trim().length() > 32){
            return "订单标签长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getOrderTag()) && !checkDictionary(ORDER_TAG,request.getOrderTag())){
            return "订单标签不合法";
        }
        if (StringUtils.isNotBlank(request.getClose())){
            if (request.getClose().trim().length() > 32){
                return "是否关闭长度不能超过32";
            }
            if (!TRUE.equals(request.getClose().trim()) && !FALSE.equals(request.getClose().trim())){
                return "是否关闭不合法";
            }
        }
        if (StringUtils.isNotBlank(request.getCloseCode()) && request.getCloseCode().trim().length() > 32){
            return "关闭编码长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getCloseCode()) && ReasonForRejectionEnum.of(request.getCloseCode().trim()) == null){
            return "关闭编码不合法";
        }
        if (StringUtils.isNotBlank(request.getReturnFlag())){
            if (request.getReturnFlag().trim().length() > 32){
                return "是否退单长度不能超过32";
            }
            if (!TRUE.equals(request.getReturnFlag().trim()) && !FALSE.equals(request.getReturnFlag().trim())){
                return "是否退单不合法";
            }
        }
        if (request.getShipMethodCode() != null && AllocateOrderShipTypeEnums.of(request.getShipMethodCode()) == null){
            return "运输方式不合法";
        }
        if (StringUtils.isNotBlank(request.getShipMethod())){
            if (request.getShipMethod().trim().length() > 32){
                return "运输方式长度不能超过32";
            }
            if (TransportModeEnum.of(request.getShipMethod()) == null){
                return "运输方式不合法";
            }
        }
        if (StringUtils.isNotBlank(request.getDeliveryLogicWareCode()) && request.getDeliveryLogicWareCode().trim().length() > 32){
            return "发货逻辑仓长度不能超过32";
        }
        if (CollectionUtils.isNotEmpty(request.getStatusList())){
            if (request.getStatusList().size() > 10){
                return "状态列表长度不能超过10";
            }
            for (String status : request.getStatusList()) {
                if (StringUtils.isBlank(status)){
                    continue;
                }
                if (status.trim().length() > 32){
                    return "状态长度不能超过32";
                }
                if (!Arrays.asList(AllocateOrderStatus.values()).stream().filter(allocateOrderStatus ->
                        AllocateOrderStatus.CLOSED_AND_PARTRECEIVED != allocateOrderStatus
                && AllocateOrderStatus.CLOSED_AND_PARTSHIPPED != allocateOrderStatus).anyMatch(allocateOrderStatus ->
                        allocateOrderStatus.getValue().toString().equals(status.trim()))) {
                    return "状态不合法";
                }
            }
        }
        if (CollectionUtils.isNotEmpty(request.getDetailStatusList())){
            if (request.getDetailStatusList().size() > 30){
                return "子单状态列表长度不能超过10";
            }
            for (String status : request.getDetailStatusList()) {
                if (StringUtils.isBlank(status)){
                    continue;
                }
                if (status.trim().length() > 32){
                    return "子单状态长度不能超过32";
                }
                if (!Arrays.asList(AllocateOrderStatus.values()).stream().filter(allocateOrderStatus ->
                        AllocateOrderStatus.CLOSED_AND_PARTRECEIVED != allocateOrderStatus
                                && AllocateOrderStatus.CLOSED_AND_PARTSHIPPED != allocateOrderStatus).anyMatch(allocateOrderStatus ->
                        allocateOrderStatus.getValue().toString().equals(status.trim()))) {
                    return "子单状态不合法";
                }
            }
        }
        //TODO 校验
//        if (CollectionUtils.isNotEmpty(request.getDeliveryLogicWarehouseCodeList())){
//
//        }
        if (StringUtils.isNotBlank(request.getReceiveLogicWareCode()) && request.getReceiveLogicWareCode().trim().length() > 32){
            return "收货逻辑仓长度不能超过32";
        }
        if (CollectionUtils.isNotEmpty(request.getDeliveryLogicWarehouseCodeList())){
            if (request.getDeliveryLogicWarehouseCodeList().size() > 10){
                return "发货仓列表个数不能超过10";
            }
            for (String code : request.getDeliveryLogicWarehouseCodeList()) {
                if (StringUtils.isNotBlank(code) && code.trim().length() > 32){
                    return "发货仓长度不能超过32";
                }
            }
        }
        if (CollectionUtils.isNotEmpty(request.getReceiveLogicWarehouseCodeList())){
            if (request.getReceiveLogicWarehouseCodeList().size() > 10){
                return "收货仓列表个数不能超过10";
            }
            for (String code : request.getReceiveLogicWarehouseCodeList()) {
                if (StringUtils.isNotBlank(code) && code.trim().length() > 32){
                    return "收货仓长度不能超过32";
                }
            }
        }
        if (StringUtils.isNotBlank(request.getDeliveryFactoryCode()) && request.getDeliveryFactoryCode().trim().length() > 32){
            return "发货仓工厂编码长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getDeliveryStorageLocationCode()) && request.getDeliveryStorageLocationCode().trim().length() > 32){
            return "发货仓库存地点长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getReceiveFactoryCode()) && request.getReceiveFactoryCode().trim().length() > 32){
            return "收货仓工厂编码长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getReceiveStorageLocationCode()) && request.getReceiveStorageLocationCode().trim().length() > 32){
            return "收货仓库存地点长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getFreightYardCode()) && request.getFreightYardCode().trim().length() > 32){
            return "货场仓编码长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getCreator()) && request.getCreator().trim().length() > 32){
            return "创建人长度不能超过32";
        }
        if (StringUtils.isNotBlank(request.getModifier()) && request.getModifier().trim().length() > 32){
            return "修改人长度不能超过32";
        }
        if (CollectionUtils.isNotEmpty(request.getGoodsCodeList())){
            if (request.getGoodsCodeList().size() > 10){
                return "物料编码列表个数不能超过10";
            }
            for (String code : request.getGoodsCodeList()) {
                if (StringUtils.isNotBlank(code) && code.trim().length() > 32){
                    return "物料编码长度不能超过32";
                }
            }
        }

        if(StringUtils.isNotEmpty(request.getGmtCreateStart())){
            if(request.getGmtCreateStart().length() != 19
                    || !CheckUtil.isLegalDate(request.getGmtCreateStart())){
                return "创建时间-开始格式应为yyyy-MM-dd HH:mm:ss";
            }
        }
        if(StringUtils.isNotEmpty(request.getGmtCreateEnd())){
            if(request.getGmtCreateEnd().length() != 19
                    || !CheckUtil.isLegalDate(request.getGmtCreateEnd())){
                return "创建时间-结束格式应为yyyy-MM-dd HH:mm:ss";
            }
        }
        if (StringUtils.isNotBlank(request.getGmtModifiedStart())){
//            if (request.getGmtModifiedStart().trim().length() > 19){
//                return "修改时间-开始时间长度不能大于19";
//            }
            if (!CheckUtil.isLegalDate(request.getGmtModifiedStart().trim())){
                return "修改时间-开始时间格式应为yyyy-MM-dd HH:mm:ss";
            }
        }
        if (StringUtils.isNotBlank(request.getGmtModifiedEnd())){
//            if (request.getGmtModifiedEnd().trim().length() > 19){
//                return "修改时间-开始时间长度不能大于19";
//            }
            if (!CheckUtil.isLegalDate(request.getGmtModifiedEnd().trim())){
                return "修改时间-结束时间格式应为yyyy-MM-dd HH:mm:ss";
            }
        }
        if (StringUtils.isNoneBlank(request.getGmtCreateStart(),request.getGmtCreateEnd())){
            if (getTimestamp(request.getGmtCreateStart(),YYYY_MM_DD_HH_MM_SS) > getTimestamp(request.getGmtCreateEnd(),YYYY_MM_DD_HH_MM_SS)){
                return "创建时间-开始时间不能晚于创建时间-结束时间";
            }
        }
        if (StringUtils.isNoneBlank(request.getGmtModifiedStart(),request.getGmtModifiedEnd())){
            if (getTimestamp(request.getGmtModifiedStart(),YYYY_MM_DD_HH_MM_SS) > getTimestamp(request.getGmtModifiedEnd(),YYYY_MM_DD_HH_MM_SS)){
                return "修改时间-开始时间不能晚于修改时间-结束时间";
            }
        }

        return null;
    }

    /**
     * 根据 仓库编码code查询仓库信息
     * @param warehouseCode code
     * @return WarehouseQueryResponse
     */
    private String getWarehouseInfo(String warehouseCode){
        WarehouseQueryRequest warehouseQueryRequest = new WarehouseQueryRequest();
        warehouseQueryRequest.setMerchantCode("mengniu");
        warehouseQueryRequest.setCode(warehouseCode);
        Result<WarehouseQueryResponse> warehouseResult = mnInventoryCenterService.queryWarehoseByCodeApi(warehouseQueryRequest);
        if(warehouseResult.getResult() == null){
//            throw new FacadeException("该仓库不存在, warehouseCode:{}",warehouseCode);
            return null;
        }
        if(warehouseResult.getResult().getId() == null){
//            throw new FacadeException("该仓库id不存在, warehouseCode:{}",warehouseCode);
            return null;
        }
        return warehouseResult.getResult().getId();
    }

    @Override
    @FacadeInvoker(value = "调拨单详情")
    public Result<TransferOrderResponse> queryTransferOrder(TransferOrderDetailsRequest request) {
        log.info("TransferOrderReadService---queryTransferOrder,request:{}",request);
        //校验
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("checkQueryNull");
        String msg = checkQueryNull(request);
        stopWatch.stop();
        if (StrUtil.isNotBlank(msg)){
            log.error("TransferOrderReadService---queryTransferOrder,checkNullError:{}",msg);
            return Result.fail( "OTS-03-001-00-15-101", msg);
        }
        //拓传
//        AllocateOrderDetailsQueryRequest allocateOrderDetailsQueryRequest = new AllocateOrderDetailsQueryRequest();
//        allocateOrderDetailsQueryRequest.setCode(request.getTransferOrderCode());
//        allocateOrderDetailsQueryRequest.setThirdAllocateOrderId(request.getThirdAllocateOrderId());
//        allocateOrderDetailsQueryRequest.setBusinessType(request.getBusinessType());
        //allocateOrderDetailsQueryRequest.setFromSys(request.getFromSys());
//        Result<AllocateOrderDetailsQueryResponse> result = allocateOrderReadService.query(allocateOrderDetailsQueryRequest);
        stopWatch.start("loadAllocateOrderList");
        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
        allocateOrderLoadListRequest.setCode(request.getTransferOrderCode());
        allocateOrderLoadListRequest.setThirdAllocateOrderId(request.getThirdAllocateOrderId());
        allocateOrderLoadListRequest.setBusinessType(request.getBusinessType());
        log.info("TransferOrderReadService---queryTransferOrder,extension request：{}",JSON.toJSONString(allocateOrderLoadListRequest));
        Result<List<AllocateOrder>> result = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
        log.info("TransferOrderReadService---queryTransferOrder,extension response：{}",JSON.toJSONString(result));
        stopWatch.stop();
        if (result == null || CollectionUtils.isEmpty(result.getResult())){
            return Result.fail( result.getErrorCode(),"调拨单不存在");
        }
        AllocateOrder allocateOrder = result.getResult().get(0);
        //查询列表
        AllocateOrderDetailSearchRequest allocateOrderDetailSearchRequest = new AllocateOrderDetailSearchRequest();
        if (StringUtils.isNotBlank(request.getTransferOrderCode())){
            allocateOrderDetailSearchRequest.setCode(request.getTransferOrderCode());
        }
        if (StringUtils.isNotBlank(request.getThirdAllocateOrderId())){
            allocateOrderDetailSearchRequest.setThirdAllocateOrderId(request.getThirdAllocateOrderId());
        }
        if (StringUtils.isNotBlank(request.getBusinessType())){
            allocateOrderDetailSearchRequest.setBusinessType(request.getBusinessType());
        }
        // 子单最多100
        allocateOrderDetailSearchRequest.setSize(100);
        stopWatch.start("queryTransferOrderSearch");
        Result<List<AllocateOrderDetailVO>> listResult = allocateOrderReadService.queryTransferOrderSearch(allocateOrderDetailSearchRequest);
        log.info("queryTransferOrderSearch_result:{}",JSON.toJSONString(listResult));
        stopWatch.stop();
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())){
            return Result.fail( result.getErrorCode(),"调拨单不存在");
        }

        TransferOrderResponse transferOrderResponse = new TransferOrderResponse();
        if (ObjectUtil.isEmpty(result.getResult())){
            return Result.success(transferOrderResponse);
        }
        //转换
        transferOrderResponse.setTransferOrderCode(allocateOrder.getCode());
        transferOrderResponse.setFromSys(allocateOrder.getFromSys());
        transferOrderResponse.setBusinessType(allocateOrder.getBusinessType());


        transferOrderResponse.setTransferOrderType(allocateOrder.getType().toString());
//        transferOrderResponse.setTransferOrderTypeName(queryResponse.getTypeDesc());

        //获取仓库
        List<String> warechouseIds = new ArrayList<>();
        if (StrUtil.isNotBlank(allocateOrder.getShipAreaId())){
            warechouseIds.add(allocateOrder.getShipAreaId());
        }
        if (StrUtil.isNotBlank(allocateOrder.getReceiveAreaId())){
            warechouseIds.add(allocateOrder.getReceiveAreaId());
        }
        QueryWarehouseByIdApiRequest queryWarehouseByIdApiRequest = new QueryWarehouseByIdApiRequest();
        queryWarehouseByIdApiRequest.setWarehouseIds(warechouseIds);
        stopWatch.start("queryWarehouseByIdApi");
        Result<List<WarehouseQueryResponse>> queryWarehouseByIdApi = mnInventoryCenterService.queryWarehouseByIdApi(queryWarehouseByIdApiRequest);
        stopWatch.stop();
        Map<String,String> idCodeMap = new HashMap<>();
        Map<String,String> idNameMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(queryWarehouseByIdApi.getResult())){
            idCodeMap = queryWarehouseByIdApi.getResult().stream().collect(Collectors.toMap(WarehouseQueryResponse::getId,WarehouseQueryResponse::getCode));
            idNameMap = queryWarehouseByIdApi.getResult().stream().collect(Collectors.toMap(WarehouseQueryResponse::getId,WarehouseQueryResponse::getName));
        }
        //
        transferOrderResponse.setDeliveryLogicWareCode(idCodeMap.get(allocateOrder.getShipAreaId()));
        transferOrderResponse.setDeliveryLogicWareName(idNameMap.get(allocateOrder.getShipAreaId()));

        transferOrderResponse.setReceiveLogicWareCode(idCodeMap.get(allocateOrder.getReceiveAreaId()));
        transferOrderResponse.setReceiveLogicWareName(idNameMap.get(allocateOrder.getReceiveAreaId()));
        //----
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (Objects.nonNull(allocateOrder.getDocDate())){
            transferOrderResponse.setOrderDate(format.format(allocateOrder.getDocDate()));
        }
        if (Objects.nonNull(allocateOrder.getExpectedDeliveryDate())){
            transferOrderResponse.setExpectedDeliveryDate(format.format(allocateOrder.getExpectedDeliveryDate()));
        }
        transferOrderResponse.setShipMethodCode(allocateOrder.getShipMethod() == null ? null : "0" +allocateOrder.getShipMethod());
        transferOrderResponse.setHeadRemark(allocateOrder.getRemark());
        transferOrderResponse.setGmtCreate(format.format(allocateOrder.getGmt_create()));
        transferOrderResponse.setCreator(allocateOrder.getCreatorName());
        transferOrderResponse.setModifier(allocateOrder.getModifierName());
        transferOrderResponse.setGmtModified(format.format(allocateOrder.getGmt_modified()));

        Map<String, OrganizationSDO> orgMap = Maps.newHashMap();
        stopWatch.start("baselineGetOrganizationByIds2");
        if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
            List<String> orgIds = listResult.getResult().stream().map(AllocateOrderDetailVO::getApplyOrgId).filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(orgIds)){
                BaselineGetOrganizationByIds2Request byIds2Request = new BaselineGetOrganizationByIds2Request();
                byIds2Request.setIds(orgIds);
                BaselineGetOrganizationByIds2Response byIds2Response = baseDataService.baselineGetOrganizationByIds2(byIds2Request);
                Nullable.stream(byIds2Response.getResult()).forEach(organizationSDO -> orgMap.put(organizationSDO.getId(),organizationSDO));
            }
        }
        stopWatch.stop();
        stopWatch.start("convert_main_order");
        if (CollectionUtils.isNotEmpty(listResult.getResult())){
            // 货场仓map
            Map<String,CargoZoneSDO> cargoZoneSDOCodeMap = Maps.newHashMap();
            if (CollectionUtils.isNotEmpty(listResult.getResult())){
                List<String> freightYardIds = listResult.getResult().stream().map(AllocateOrderDetailVO::getFreightYardId).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
                //这里是code
                log.info("getCargoZoneSDOMap_request:{}",JSON.toJSONString(freightYardIds));
                if (CollectionUtils.isNotEmpty(freightYardIds)){
                    Map<String, CargoZoneSDO> zoneSDOMap = warehouseConvert.getCargoZoneSDOMapByCodes(freightYardIds);
                    if (MapUtils.isNotEmpty(zoneSDOMap)){
                        cargoZoneSDOCodeMap.putAll(zoneSDOMap);
                    }
                }
            }

            AllocateOrderDetailVO vo = listResult.getResult().get(0);
            transferOrderResponse.setFromSys(vo.getFromSys());
            transferOrderResponse.setBusinessType(vo.getBusinessType());
            transferOrderResponse.setThirdAllocateOrderId(vo.getThirdAllocateOrderId());
            transferOrderResponse.setOutOrderCode(vo.getOutAllocateOrderId());
            //主单features
            if (StringUtils.isNotBlank(allocateOrder.getBizFeatures())){
                transferOrderResponse.setHeadFeatures(JSON.toJSONString(FeatureUtil.fromString(allocateOrder.getBizFeatures())));
            }
            transferOrderResponse.setAllocateApplyOrderCode(vo.getAllocateApplyOrderCode());
            transferOrderResponse.setRelatedAllocateOrderCode(vo.getRelatedAllocateOrderCode());
            transferOrderResponse.setTransferOrderType(vo.getType() == null ? null :vo.getType().toString());
            OrganizationSDO organizationSDO = orgMap.get(vo.getApplyOrgId());
            if (organizationSDO != null){
                transferOrderResponse.setApplyOrgId(organizationSDO.getCode());
            }

            transferOrderResponse.setProductGroupCode(vo.getProductGroup());
            transferOrderResponse.setFulfillmentTypeCode(vo.getFulfillmentTypeCode());
            transferOrderResponse.setAutoFulfillment(vo.getAutoFulfillment() == null ? "" : vo.getAutoFulfillment().toString());
            transferOrderResponse.setPriority(vo.getPriority() == null ? "" :vo.getPriority().toString());
            transferOrderResponse.setOrderTag(StringUtils.isBlank(vo.getOrderTag()) ? Lists.newArrayList() :
                    Arrays.asList(vo.getOrderTag().split(",")));

            transferOrderResponse.setDeliveryWarehouseCode(vo.getShipWarehouseCode());
            transferOrderResponse.setDeliveryWarehouseName(vo.getShipWarehouseName());
            transferOrderResponse.setDeliveryFactoryCode(vo.getShipFactoryCode());
            transferOrderResponse.setDeliveryStorageLocationCode(vo.getShipInventoryCode());
            transferOrderResponse.setReceiveWarehouseCode(vo.getReceiveWarehouseCode());
            transferOrderResponse.setReceiveWarehouseName(vo.getReceiveWarehouseName());
            transferOrderResponse.setReceiveFactoryCode(vo.getReceiveFactoryCode());
            transferOrderResponse.setReceiveStorageLocationCode(vo.getReceiveInventoryCode());
            transferOrderResponse.setReceiveWarehouseContactor(vo.getReceiveAreaContactor());
            transferOrderResponse.setReceiveWarehousePhone(vo.getReceiveAreaPhone());
            transferOrderResponse.setReceiveWarehouseAddress(vo.getReceiveAreaAddress());
            CargoZoneSDO freightYard = cargoZoneSDOCodeMap.get(vo.getFreightYardId());
            if (freightYard  != null){
                transferOrderResponse.setFreightYardCode(freightYard.getCode());
                transferOrderResponse.setFreightYardName(freightYard.getName());
            }
            transferOrderResponse.setFreightYardReceive(vo.getFreightYardReceive());
//            transferOrderResponse.setFreightYardCode(vo.getFreightYardCode());
//            transferOrderResponse.setFreightYardName(vo.getFreightYardName());
            transferOrderResponse.setStatus(vo.getStatus() == null ? null : vo.getStatus().toString());
//            transferOrderResponse.setCreator(vo.getMainCreator());
            transferOrderResponse.setGmtCreate(vo.getCreateTime() == null ? null : DateFormatUtil.toString(vo.getCreateTime(),YYYY_MM_DD_HH_MM_SS));
            transferOrderResponse.setUpdater(vo.getMainUpdater());
            transferOrderResponse.setGmtModified(vo.getUpdateTime() == null ? null : DateFormatUtil.toString(vo.getCreateTime(),YYYY_MM_DD_HH_MM_SS));
            transferOrderResponse.setTakeEffectTime(vo.getDocDateStr());
            transferOrderResponse.setOrderDate(vo.getDocDateStr());
            transferOrderResponse.setExpectedDeliveryDate(vo.getExpectedDeliveryDateStr());
            transferOrderResponse.setShipMethodCode(vo.getShipMethod());
            transferOrderResponse.setShipMethodName(vo.getShipMethodDesc());
            transferOrderResponse.setHeadRemark(vo.getRemark());
            transferOrderResponse.setReturnOrder(Boolean.TRUE.equals(vo.getReturnOrder()) ? "1" :"0");
            transferOrderResponse.setHeadRemark(vo.getRemark());
            transferOrderResponse.setOutAllocateApplyOrderCode(vo.getOutAllocateApplyOrderId());

        }
        stopWatch.stop();
        stopWatch.start("convert_line");
        //明细
        List<TransferOrderDetailsResponse> detailsList = listResult.getResult().stream()
                .map(line -> {
                    TransferOrderDetailsResponse details = new TransferOrderDetailsResponse();
//                    details.setGoodsId(allocateOrderScItemDetailDTO.getScItemId());
                    details.setGoodsCode(line.getScItemCode());
                    details.setGoodsName(line.getScItemName());
                    if (ObjectUtil.isNotEmpty(line.getQuantity())){
                        details.setQuantity(line.getQuantity());
                    }
                    details.setDetailNo(line.getLineNo());
//                    details.setDetailRemark(allocateOrderScItemDetailDTO.getRemark());
//                    details.setCreator(allocateOrderScItemDetailDTO.getCreator());
//                    details.setGmtCreate(format.format(queryResponse.getCreateTime()));
//                    details.setModifier(allocateOrderScItemDetailDTO.getUpdator());
//                    details.setGmtModified(format.format(queryResponse.getUpdateTime()));
                    details.setThirdDetailLineNo(line.getThirdDetailLineNo());
                    details.setOutDetailLineNo(line.getOutAllocateOrderLineId());
                    details.setOutOrderLineNo(line.getOutAllocateOrderLineId());
                    details.setAllocateApplyDetailLineNo(line.getAllocateApplyDetailLineNo());
                    details.setRelatedAllocateSubOrderId(line.getRelatedAllocateSubOrderId());
                    details.setDetailStatus(line.getDetailStatus() == null ? null : line.getDetailStatus().toString());
                    details.setGoodsCode(line.getScItemCode());
                    details.setConfirmQuantity(line.getConfirmQuantity());
                    details.setUnit(line.getUnit());
                    details.setUnitPrice(line.getUnitPrice());
                    details.setProductDate(line.getProductDateStr());
                    details.setProduceDate(line.getProductDateStr());
                    details.setClosed(line.getClosed());
                    details.setCloseCode(line.getCloseCode());
                    details.setCloseReason(line.getCloseReason());
                    details.setDetailRemark(line.getLineRemark());
                    if(StringUtils.isNotBlank(line.getDetailFeatures())) {
                        Features features = Features.newFeatures(line.getDetailFeatures());
                        details.setDetailFeatures(JSON.toJSONString(features.getOriginMap()));
                    }
                    //小计金额
                    details.setSubTotalAmount(line.getSubTotalAmount());
                    //期待交货日期
                    details.setExpectedDeliveryDate(line.getExpectedDeliveryDateStr());
                    return details;
                }).collect(Collectors.toList());
        stopWatch.stop();
        transferOrderResponse.setTransferOrderDetailList(detailsList);
        ToolUtil.addEmptyString(transferOrderResponse);
        Nullable.stream(transferOrderResponse.getTransferOrderDetailList()).forEach(ToolUtil::addEmptyString);
        log.info("TransferOrderReadService---queryTransferOrder,response:{}",transferOrderResponse);
        Result<TransferOrderResponse> success = Result.success(transferOrderResponse);
        success.setTotal(1);
        fillResult(success);
        log.info("queryTransferOrder_cost," + stopWatch.prettyPrint());
        return success;
    }


    private String checkQueryNull(TransferOrderDetailsRequest request) {
        if (StrUtil.isBlank(request.getTransferOrderCode()) && StrUtil.isBlank(request.getThirdAllocateOrderId())){
            return "中台调拨单号和来源单号二选一必填";
        }
        if (StrUtil.isNotBlank(request.getTransferOrderCode())) {
            if (request.getTransferOrderCode().trim().length() > 32) {
                return "中台调拨单号字段长度不能大于32";
            }
        }
        if (StrUtil.isNotBlank(request.getThirdAllocateOrderId())) {
            if (request.getThirdAllocateOrderId().trim().length() > 32) {
                return "来源单号字段长度不能大于32";
            }
        }
        if (StrUtil.isBlank(request.getBusinessType())){
            return "业态编码不能为空";
        }
        if (request.getBusinessType().trim().length() > 16){
            return "业态编码长度不能大于16";
        }
        if (StrUtil.isBlank(request.getFromSys())){
            return "来源系统编码不能为空";
        }
        if (request.getFromSys().trim().length() >16){
            return "来源系统编码长度不能大于16";
        }
        if (!checkDictionary(FROM_SYS_GROUP,request.getFromSys())){
            return "来源系统编码不合法";
        }
        if (!checkDictionary(BUSINESS_TYPE_GROUP,request.getBusinessType())){
            return "业态编码不合法";
        }
        return null;
    }

    /**
     * 校验字典
     * @param group
     * @param code
     * @return
     */
    private boolean checkDictionary(String group, String code) {
        DictionaryQueryRequest request = new DictionaryQueryRequest();
        request.setGroup(group);
        Result<List<DictionaryResponse>> result = mnInventoryCenterService.queryDictionaryDataListApi(request);
        Set<String> businessTypeSet = result.getResult().stream()
                .map(DictionaryResponse::getCode)
                .collect(Collectors.toSet());
        return businessTypeSet.contains(code);
    }

    public static Long getTimestamp(String dateStr,String format){
        if (StringUtils.isAnyBlank(dateStr,format)){
            return null;
        }
        try {
            return new SimpleDateFormat(format).parse(dateStr).getTime();
        }catch (Throwable throwable){
            return null;
        }
    }

    public static boolean isValidDate(String dateStr, String format){
        if (StringUtils.isAnyBlank(dateStr,format)){
            return false;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        try {
            LocalDate.parse(dateStr, formatter);
            return true;
        }catch (Throwable e){
        }
        return false;
    }
    private void fillResult(Result result){
        Optional.ofNullable(result).ifPresent(res -> {
            if (StringUtils.isBlank(res.getErrorCode())){
                res.setErrorCode("");
            }
            if (StringUtils.isBlank(res.getMessage())){
                res.setMessage("");
            }
        });
    }
}
